package com.loukou.lkt.lkt.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.loukou.lkt.lkt.bo.GoodsBo;
import com.loukou.lkt.lkt.bo.PageList;
import com.loukou.lkt.lkt.bo.Query;
import com.loukou.lkt.lkt.constant.Urls;
import com.loukou.lkt.lkt.dao.GoodsCostDao;
import com.loukou.lkt.lkt.dao.GoodsDao;
import com.loukou.lkt.lkt.dao.GoodsStockDao;
import com.loukou.lkt.lkt.entity.Goods;
import com.loukou.lkt.lkt.entity.GoodsCost;
import com.loukou.lkt.lkt.entity.GoodsStock;
import com.loukou.lkt.lkt.enums.GoodsStockStateEnum;
import com.loukou.lkt.lkt.req.WmsGoodsReq;
import com.loukou.lkt.lkt.resp.RespDto;
import com.loukou.lkt.lkt.service.GoodsService;
import com.loukou.lkt.lkt.utils.PostUtils;


@Service
public class GoodsServiceImpl implements GoodsService{

	@Autowired
	private GoodsStockDao goodsStockDao;
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private GoodsCostDao goodsCostDao;
	
	private Logger logger = Logger.getLogger(GoodsServiceImpl.class);
	/**
	 * 商品选则
	 * warehouseId ：仓库
	 * positionType ： 库区类型
	 * sku ： 货号
	 * */
	@Override
	public RespDto<PageList<GoodsBo>> goodsPageList(int warehouseId, int positionType, final String sku,
			final String barcode, final String goodsName,int pageIndex,int pageSize) {
		RespDto<PageList<GoodsBo>> resp = new RespDto<PageList<GoodsBo>>();
		PageList<GoodsBo> pagelist =new PageList<GoodsBo>();
		resp.setResult(pagelist);
		List<GoodsStock> goodsStocks = Lists.newArrayList();
		if(warehouseId>0){
			goodsStocks = goodsStockDao.findByWarehouseIdAndPositionType(warehouseId,positionType);
		}else{
			return resp;
		}
		
		final List<Integer> goodsIds = Lists.newArrayList();
		for(GoodsStock goodsStock:goodsStocks){
			goodsIds.add(goodsStock.getGoodsId());
		}
		if(CollectionUtils.isEmpty(goodsIds)){
			return resp;
		}
//		final List<Integer> goodsIds = Lists.newArrayList();
//		if(!StringUtils.isNullOrEmpty(goodsName)){
//			List<Goods> goodss = goodsDao.findByGoodsNameLike("%"+goodsName+"%");
//			for(Goods goods : goodss){
//				goodsIds.add(goods.getGoodsId());
//			}
//			if(CollectionUtils.isEmpty(goodsIds)){
//				return resp;
//			}
//		}
		Page<Goods> goodss = goodsDao.findAll(new Specification<Goods>() {
			@Override
			public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Query<Goods> q = new Query<Goods>(cb, root, query);
				q.like("sku", sku);
				q.like("goodsName", goodsName);
				q.like("barcode",barcode);
				q.in("goodsId", goodsIds);
//				q.in("goodsId", goodsIds);
				return q.toPredicate();
			}
		}, new PageRequest(pageIndex - 1, pageSize));
		
		
		List<GoodsBo> bolists = Lists.newArrayList();
		List<Integer> goodsIdsN = Lists.newArrayList();
//		List<Integer> goodsSpecIdsN = Lists.newArrayList();
		for(Goods spec :goodss){
			goodsIdsN.add(spec.getGoodsId());
		}
		if(CollectionUtils.isEmpty(goodsIdsN)){
			return resp;
		}
		//List<Goods> namegoodss = goodsDao.findByGoodsIdIn(goodsIdsN);
//		Map<Integer,Goods> goodsNameMap = new HashMap<Integer,Goods>();
//		for(Goods goods:namegoodss){
//			goodsNameMap.put(goods.getGoodsId(),goods);
//		}
		List<GoodsStock> stockgoodss = goodsStockDao.findByWarehouseIdAndPositionTypeAndGoodsIdIn(warehouseId, positionType, goodsIdsN);
		for(Goods goods :goodss){
			GoodsBo bo = new GoodsBo();
			BeanUtils.copyProperties(goods, bo);
//			Goods goods = goodsNameMap.get(spec.getGoodsId());
//			if(goods!=null){
//				BeanUtils.copyProperties(goods, bo);
//			}
			GoodsCost cost = goodsCostDao.getGoodsCost(goods.getGoodsId());
			if(cost!=null){
				bo.setCostPrice(cost.getCostPrice());
			}
			int curStock = 0;
			int curFreezeStock = 0;
			int curUseStock = 0;
			for(GoodsStock goodsstock : stockgoodss){
				if(goodsstock.getGoodsId() == goods.getGoodsId()){
					curStock+=goodsstock.getStock();//库存
					if(goodsstock.getStockState() == GoodsStockStateEnum.STATE_Normal.getId()){
						//可用库存
						curUseStock+=goodsstock.getStock();
					}else{
						//冻结库存
						curFreezeStock+=goodsstock.getStock();
					}
				}
			}
			bo.setWarehouseId(warehouseId);
			bo.setPositionType(positionType);
			bo.setCurFreezeStock(curFreezeStock);
			bo.setCurStock(curStock);
			bo.setCurUseStock(curUseStock);
			bolists.add(bo);
		}
		pagelist.setEntityList(bolists);
		pagelist.setCurPageIndex(pageIndex);
		pagelist.setPageCount(goodss.getTotalPages());
		pagelist.setRecordCount(goodss.getTotalElements());
		resp.setResult(pagelist);
		return resp;
	}
	@Override
	public GoodsBo getGoods(int warehouseId, int positionType, int goodsId) {
		GoodsBo bo = new GoodsBo();
        Goods goods= goodsDao.findByGoodsId(goodsId);
        if(goods==null){
        	return bo;
        }
//        Goods goods = goodsDao.findOne(spec.getGoodsId());
		List<GoodsStock> stockgoodss = goodsStockDao.findByWarehouseIdAndPositionTypeAndGoodsIdIn(warehouseId, positionType, Arrays.asList(goodsId));
		if(CollectionUtils.isEmpty(stockgoodss)){
			return null;
		}
		BeanUtils.copyProperties(goods, bo);
//		if(goods!=null){
//			BeanUtils.copyProperties(goods, bo);
//		}
		GoodsCost cost = goodsCostDao.getGoodsCost(goods.getGoodsId());
		if(cost!=null){
			bo.setCostPrice(cost.getCostPrice());
		}
		int curStock = 0;
		int curFreezeStock = 0;
		int curUseStock = 0;
		for(GoodsStock goodsstock : stockgoodss){
			if(goodsstock.getGoodsId() == goods.getGoodsId()){
				curStock+=goodsstock.getStock();//库存
				if(goodsstock.getStockState() == GoodsStockStateEnum.STATE_Normal.getId()){
					//可用库存
					curUseStock+=goodsstock.getStock();
				}else{
					//冻结库存
					curFreezeStock+=goodsstock.getStock();
				}
			}
		}
		bo.setWarehouseId(warehouseId);
		bo.setPositionType(positionType);
		bo.setCurFreezeStock(curFreezeStock);
		bo.setCurStock(curStock);
		bo.setCurUseStock(curUseStock);
	   return bo;
	}
	@Override
	public Goods getGoods(String sku) {
		return goodsDao.findBySku(sku);
	}
	
	@Override
	public void pushGoodsToWms() {
		Sort sort = new Sort(Sort.Direction.ASC, "goodsId");
		Pageable pageable = new PageRequest(0, 100, sort);
		List<Goods> goodsList = goodsDao.findByIsPush(0, pageable);
		if(goodsList == null || goodsList.size() == 0){
			return;
		}
		List<WmsGoodsReq> wmsGoodsList = new ArrayList<WmsGoodsReq>();
		for(Goods goods: goodsList){
//			Goods goods = goodsDao.findOne(goodsSpec.getGoodsId());
//			if(goods == null){
//				continue;
//			}
			WmsGoodsReq wmsGoodsReq = new WmsGoodsReq();
			wmsGoodsReq.setBarcode(goods.getBarcode());
			wmsGoodsReq.setCustomerGoodsId(""+goods.getGoodsId());
			wmsGoodsReq.setGoodsName(goods.getGoodsName());
			wmsGoodsReq.setSku(goods.getSku());
			wmsGoodsReq.setCustomerNo("lkt");
			wmsGoodsList.add(wmsGoodsReq);
		}
		Map<String, String> resp = (Map<String, String>) PostUtils.postData(Urls.PushGoodsToWms, wmsGoodsList);
		if(resp == null){
			logger.error("推送商品返回信息为空");
			return;
		}
		if("200".equals(resp.get("code"))){
			for(Goods goods: goodsList){
				goods.setIsPush(1);
				goodsDao.save(goods);
			}
		}else{
			logger.error("推送商品到WMS返回错误信息："+ resp.get("errorMsg"));
		}
	}
	@Override
	public void saveGoodsList(List<Goods> goodsList) {
		goodsDao.save(goodsList);
	}
	
}
